﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Xml.Linq;
using Samples.Radio.Agent;
using Samples.Radio.Agent.Data;
using Samples.Radio.Helpers;

namespace Samples.Radio.Data
{
    public class RadioRepository:Repository

    {
        INowPlayingService _nowPlayingService;

        public INowPlayingService NowPlayingService
        {
            get
            {
                {
                    if (_nowPlayingService == null)
                    {
                        LoadPlayerService();
                    }
                    return _nowPlayingService;
                }
            }
        }

        public event EventHandler<ParameterEventArgs<ProgramViewModel[]>> LoadProgramsCompleted;
        public event EventHandler TrackInformationUpdated;

        public void LoadPlayerService()
        {
            #region Example of implementing now playing using 'Triple J'
            //_nowPlayingService = new PlayoutPlayingService();
            #endregion

            #region Example Of implementing now playing using 'Absolute radio'

            _nowPlayingService = new AbsoluteRadioPlayingService(this) {NumberRecentTracksToDisplay = 4};

            #endregion

            _nowPlayingService.TracksUpdated += (s, e) =>
            {
                TrackInformationUpdated.SafeRaise(this);
                //_nowPlayingService.UpdateLiveTile();
            };
        }

        /// <summary>
        /// Load all the programs for the station
        /// </summary>
        /// <param name="xmlUrl"></param>
        public void LoadPrograms()
        {
            var xmlUrl = Configuration.ProgramUrl;
            var client = new WebClient();
            client.OpenReadCompleted += (sender, e) =>
            {
                if (e.Error != null)
                    return;

                using (var str = e.Result)
                {
                    var programsDataXml = XDocument.Load(str);
                    var programsData = (from query in programsDataXml.Descendants("Program")
                                        select new ProgramViewModel
                                                   {
                                                       ProgramName = (string) query.Element("Name"),
                                                       Description = (string) query.Element("Description"),
                                                       Presenters = (string) query.Element("Presenters"),
                                                       StartTime = (string) query.Element("StartTime"),
                                                       EndTime = (string) query.Element("EndTime"),
                                                       AssociatedPodcastUrl =
                                                           (string) query.Element("AssociatedPodcastUrl"),
                                                       ProgramImage = (string) query.Element("AssociatedImageUrl"),
                                                       ProgramSlogan = (string) query.Element("ProgramSlogan"),
                                                       Keywords = (string) query.Element("Keywords"),
                                                       Schedule =
                                                           (string) query.Element("StartTime") + " - " +
                                                           (string) query.Element("EndTime")
                                                       //PublishedDate = DateTime.Parse((string)query.Element("pubDate"))
                                                   }).ToArray();



                    LoadProgramsCompleted.SafeRaise(this, programsData);
                }
                
            };
            client.OpenReadAsync(new Uri(xmlUrl, UriKind.Absolute));
        }

        public void AddPodcastToPlaylist(PodcastViewModel selectedPodcast)
        {
            var track = selectedPodcast.ToPlaylistTrack();
            NowPlayingService.AddTrackToPlaylist(track);
        }
    }
}
